<template>
  <div class="app-container home" v-loading="loading">

    <el-form :model="queryParams" :inline="true">
        <el-form-item label="查询基准">
          <el-radio-group v-model="queryParams.dataType" @change="radioChange">
            <el-radio label="D">日别</el-radio>
            <el-radio label="W">周别</el-radio>
            <el-radio label="M">月别</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="时间" prop="startTime" label-width="40px">
          <div v-if="queryParams.dataType === 'D'">
            <WeekTimePicker type="date" v-model="queryParams.startTime" :options="disabledOptionsTwo" :clearable="false" style="width: 130px"/> <span style="margin: 0 4px;">~</span>
            <WeekTimePicker type="date" v-model="queryParams.endTime" :options="disabledOptions" :clearable="false" style="width: 130px"/>
          </div>

          <div v-if="queryParams.dataType === 'W'">
            <WeekTimePicker type="date" v-model="queryParams.startTime" :options="disabledOptions" :clearable="false" style="width: 130px" @onChange="timeChange"/>
            <span style="margin-left: 10px; font-size: 12px; font-weight: 5 00;">{{ titleWeek }}</span>
          </div>

          <div v-if="queryParams.dataType === 'M'">
            <DatePicker type="month" v-model="queryParams.startTime" :options="disabledOptions" size="small" placeholder="Select month" style="width: 130px" :clearable="false"/>
          </div>
        </el-form-item>

        <el-form-item label="显示基准">
          <el-checkbox-group v-model="showBase" :min="1" @change="showBaseChange">
            <el-checkbox v-for="group in groups" :key="group" :label="group">{{ group }}</el-checkbox>
          </el-checkbox-group>

          <el-button style="margin-left: 100px;" type="primary" @click="getData" v-hasPermi="['system:INFO:query']">查询</el-button>
          <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:INFO:export']">导出</el-button>
        </el-form-item>
    </el-form>

    <t-ag-grid
      style="height: calc(100% - 80px);"
      align="center"
      header-align="center"
      :suppress-row-transform="true"
      :tooltipShowDelay="0"
      :columnDefs="tableColumn"
      :rowData="tableData"
      :defaultColDef = "{
        // suppressMenu:true
        menuTabs: ['filterMenuTab', 'columnsMenuTab'],
        filter: 'agMultiColumnFilter'
      }"
      @cell-clicked="onCellClicked"
    />
  </div>
</template>

<script setup name="KpiInfo">
  import { reactive, watch } from 'vue'
  import moment from 'moment'
  const { proxy } = getCurrentInstance()
  import { listINFO, column, firstColumn, secondColumn, thirdColumn, fourthColumn, othersColumn, getParentInfo } from './config'
  import { useRouter } from 'vue-router'

  const router = useRouter()

  const queryParams = reactive({
    dataType: 'D',
    startTime: moment().unix() > moment(moment().format('YYYY-MM-DD 10:30:00')).unix() ? moment().subtract(1, 'days').format('YYYY-MM-DD') : moment().subtract(2, 'days').format('YYYY-MM-DD'),
    endTime: moment().unix() > moment(moment().format('YYYY-MM-DD 10:30:00')).unix() ? moment().format('YYYY-MM-DD') : moment().subtract(1, 'days').format('YYYY-MM-DD')
    // (moment().unix() > moment(moment().format('YYYY-MM-DD 10:30:00')).unix() ? moment().valueOf() : moment().subtract(1, 'days').valueOf())
  })
  const loading = ref(false)
  const showBase = ref(['基础指标(综合效率/标准节拍/产能/生产量/Trace统计/品质)', '时间稼动损失率(%)', '时间稼动损失时(分)', '时间稼动损失数(件)', '其他参考指标'])
  const groups = ['基础指标(综合效率/标准节拍/产能/生产量/Trace统计/品质)', '时间稼动损失率(%)', '时间稼动损失时(分)', '时间稼动损失数(件)', '其他参考指标']

  const freezeData = [
    {
      headerName: "设备组", field: "eqpGroup", width: 100, pinned: 'left'
    },
    {
      headerName: "设备ID", field: "eqpId", width: 100, pinned: 'left'
    }
  ]
  const titleWeek = ref('')
  const tableColumn = ref([])
  const tableData = ref([])

  tableColumn.value = [
    ...freezeData,
    ...column('D')
  ]

  let obj = {
    '基础指标(综合效率/标准节拍/产能/生产量/Trace统计/品质)': firstColumn,
    '时间稼动损失率(%)': secondColumn,
    '时间稼动损失时(分)': thirdColumn,
    '时间稼动损失数(件)': fourthColumn,
    '其他参考指标': othersColumn
  }

  const showBaseChange = (val) => {
    tableColumn.value = [...freezeData]
    groups.forEach((item) => {
      if(val.includes(item)){
        tableColumn.value.push(...obj[item])
      }
    })
  }

  const disabledOptions = {
    disabledDate (date) {
      // return date && date.valueOf() > moment().valueOf()
      return date && date.valueOf() > (moment().unix() > moment(moment().format('YYYY-MM-DD 10:30:00')).unix() ? moment().valueOf() : moment().subtract(1, 'days').valueOf())
    }
  }

  const disabledOptionsTwo = {
    disabledDate (date) {
      // return date && date.valueOf() > moment().subtract(1, 'day').valueOf()
      return date && date.valueOf() > (moment().unix() > moment(moment().format('YYYY-MM-DD 10:30:00')).unix() ? moment().subtract(1, 'days').valueOf() : moment().subtract(2, 'days').valueOf())
    }
  }

  const timeChange = () => {
    titleWeek.value = `${moment(queryParams.startTime).year()} 年 第 ${moment(queryParams.startTime).week()} 周`
  }

  const radioChange = (val) => {
    if(val === 'W'){
      titleWeek.value = `${moment(queryParams.startTime).year()} 年 第 ${moment(queryParams.startTime).week()} 周`
    }
    if(val === 'D'){
      queryParams.startTime = moment().subtract(1, 'day').format('YYYY-MM-DD')
      queryParams.endTime = moment().format('YYYY-MM-DD')
    }

  }

  let timeBegin = null
  let timeEnd = null

  const getData = () => {
    if(queryParams.dataType === 'W'){
      timeBegin = moment(moment(queryParams.startTime).format("YYYY-MM-DD")).startOf('week').format("YYYY-MM-DD")
      timeEnd = null
    } else if (queryParams.dataType === 'M'){
      timeBegin = moment(moment(queryParams.startTime).format("YYYY-MM-DD")).startOf('month').format("YYYY-MM-DD")
      timeEnd = null
    } else if (queryParams.dataType === 'D'){
      timeBegin = moment(queryParams.startTime).format("YYYY-MM-DD")
      timeEnd = moment(queryParams.endTime).format("YYYY-MM-DD")
    }

    tableColumn.value = [
      ...freezeData,
      ...column(queryParams.dataType)
    ]

    loading.value = true
    listINFO({
      dataType: queryParams.dataType,
      startTime: timeBegin,
      endTime: timeEnd,
      pageNum: 1,
      pageSize: 1000
    }).then((res) => {
      tableData.value = res.rows
      loading.value = false
    })
  }

  let _temp = ['OEE实绩(%)', '时间稼动率(%)', 'ST目标(秒/片)']

  const onCellClicked = ({ data, colDef, value }) => {
    if(data.eqpId !== 'BY MBB' && data.eqpId !== 'BY 叠瓦' && _temp.includes(colDef.headerName)){

      getParentInfo({
        machineId: data.eqpId
      }).then((res) => {
        if(colDef.headerName === 'OEE实绩(%)' && queryParams.dataType === 'D'){
          if(data.eqpGroup === 'MBB'){
            router.push({
              path: '/PRDMonitor/beforeLayer/MBB',
              state: {
                selectedEpt: [res.设备区域],
                dataTime: moment(queryParams.startTime).format('YYYY-MM-DD')
              }
            })
          }

          if(data.eqpGroup === '叠瓦'){
            router.push({
              path: '/PRDMonitor/beforeLayer/imbricate',
              state: {
                selectedEpt: [res.设备区域],
                dataTime: moment(queryParams.startTime).format('YYYY-MM-DD')
              }
            })
          }
        }

        if(colDef.headerName === '时间稼动率(%)'){
          let state = {
            factoryAreaId: res.制造区域,
            productionTypeId: res.制造类型,
            topId: [data.eqpId],
            startTime: moment(queryParams.startTime).format('YYYY-MM-DD 08:30:00'),
            endTime: moment(queryParams.endTime).format('YYYY-MM-DD 08:30:00')
          }
          if(queryParams.dataType === 'W') {
            state.startTime = moment(moment(queryParams.startTime).format("YYYY-MM-DD")).startOf('week').format("YYYY-MM-DD 08:30:00")
            // state.endTime = moment(moment(queryParams.startTime).format("YYYY-MM-DD")).startOf('week').add(7, 'days').format("YYYY-MM-DD 08:30:00")

            if(moment(moment(queryParams.startTime).format("YYYY-MM-DD 08:30:00")).startOf('week').add(7, 'days').unix() > moment(moment().format('YYYY-MM-DD 08:30:00')).unix()){
              state.endTime = moment().format('YYYY-MM-DD 08:30:00')
            } else {
              state.endTime = moment(moment(queryParams.startTime).format("YYYY-MM-DD")).startOf('week').add(7, 'days').format("YYYY-MM-DD 08:30:00")
            }

          }

          if(queryParams.dataType !== 'M') {
            router.push({
              path: '/timeAnalysis/oeeTimeHistory',
              state
            })
          }
          // if(queryParams.dataType === 'M') {
          //   state.startTime = moment(moment(queryParams.startTime).format("YYYY-MM-DD")).startOf('month').format("YYYY-MM-DD  08:30:00")
          //   state.endTime = moment(moment(queryParams.startTime).format("YYYY-MM-DD")).startOf('month').add(1, 'month').format("YYYY-MM-DD  08:30:00")
          // }

          // router.push({
          //   path: '/timeAnalysis/oeeTimeHistory',
          //   state
          // })
        }

        if(colDef.headerName === 'ST目标(秒/片)' && queryParams.dataType === 'D'){
          router.push({
            path: '/indexAnalyse/astAnalysis/machineAST',
            state: {
              machineTypeId: res.设备类型,
              mainLineName: data.eqpId,
              dataTime: moment(queryParams.startTime).format('YYYY-MM-DD')
            }
          })
        }

      })
    }
  }

  const handleExport = () => {
    proxy.download('system/INFO/export', {
      dataType: queryParams.dataType,
      startTime: timeBegin,
      endTime: timeEnd
    }, `KPI综合情报_${new Date().getTime()}.xlsx`)
  }

</script>

<style lang="less" scoped>
// :deep(.ag-header-cell-text) {
//   margin-left: 16px;
// }

:deep(.custom-rate) {
  background-color: #ddebf7;
}

:deep(.custom-mins) {
  background-color: #a8d08d;
}

:deep(.custom-common) {
  background-color: #fce4d6;
}

:deep(.custom-color) {
  color: red;
}

.el-radio {
  margin-right: 8px;
}
// .el-checkbox {
//   margin-right: 8px;
// }

</style>